package com.ruoyi.common.utils;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

public class CsjSignUtils {
        static class Req {
            String appID;
            String signType;
            String version;
            long timestamp;
            String reqID;
            String data;
            String sign;

            Req(String appID, String signType, long timestamp, String reqID, String data) {
                this.appID = appID;
                this.signType = signType;
                this.timestamp = timestamp;
                this.reqID = reqID;
                this.data = data;
            }
        }


        static String md5(String data) {
            try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                byte[] md5 = md.digest(data.getBytes(StandardCharsets.UTF_8));

                StringBuilder sb = new StringBuilder();
                for (byte b : md5) {
                    sb.append(String.format("%02x", b));
                }
                return sb.toString();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
                throw null;
            }
        }

        public static String getSign(Req req) {
            final String secureKey = "kLFJLPsxnFXxkJ2b6QvVk_yOx0L-OE6GR_eu7ZjMMIc=";
            String signStr = String.format("app_id=%s&data=%s&req_id=%s&timestamp=%d%s", req.appID, req.data,
                    req.reqID, req.timestamp, secureKey);
            return md5(signStr);
        }

        public static void main(String[] args) {
            String data = "{\n" +
                    "    \"app_id\": \"5738866\",\n" +
                    "    \"timestamp\": 1757323986,\n" +
                    "    \"version\": \"1\",\n" +
                    "    \"sign\": \"812c369dc9dd5ae0a6391dbc7c9bba0f\",\n" +
                    "    \"sign_type\": \"MD5\",\n" +
                    "    \"req_id\": \"162191bb-243d-472f-9135-62cea91c4f16\",\n" +
                    "    \"data\": \"{\\\"page\\\": 0, \\\"page_size\\\": 15}\"\n" +
                    "}";
            String uuid=UUID.randomUUID().toString();
            long time=System.currentTimeMillis() / 1000;
            System.out.printf("time: %s\n", time);
            System.out.printf("uuid: %s\n", uuid);
            Req req = new Req("5738866", "MD5", time, uuid, data);
            req.sign = getSign(req);
            System.out.printf("sign: %s\n", req.sign);
            // serialize req to json
        }

}
